/**
 * 
 */
package info.niwota.web.apache;

import java.util.Locale;

import info.niwota.web.SessionManager;
import x.org.apache.http.Header;
import x.org.apache.http.HttpRequest;
import x.org.apache.http.HttpResponse;
import x.org.apache.http.protocol.HttpContext;
import android.net.Uri;
import android.text.TextUtils;

/**
 * @author qiangli
 * 
 */
public final class HttpUtils {

	private HttpUtils() {
	}

	public static void setCookies(HttpResponse res, String cookies) {
		// Set-Cookie: name=xxxx; expires=date; path=/;
		// "Set-Cookie: "+ cookies + "\r\n";

		res.addHeader("Set-Cookie", cookies);
	}

	public static Header[] getCookies(HttpRequest req) {
		Header[] cookies = req.getHeaders("Cookie");
		return cookies;
	}

	public static void setSessionCookie(HttpResponse res, String sid) {
		// "Set-Cookie: sid=" + cid +"; path=/;\r\n";
		res.addHeader("Set-Cookie", BaseHandler.SESSION_ID_KEY + "=" + sid
				+ "; path=/;");
	}

	public static String filterCookies(String pkg, Header[] cookies) {
		if (cookies == null || cookies.length == 0) {
			return null;
		}
		final String pname = pkg + ".";
		final int plen = pname.length();
		StringBuilder sb = new StringBuilder();
		final String sep = ";";
		for (int i = 0; i < cookies.length; i++) {
			String n = cookies[i].getName();
			String v = cookies[i].getValue();
			if (n.startsWith(pname)) {
				sb.append(n.substring(plen) + "=" + v + sep);
			}
		}
		return (sb.length() > 0 ? sb.toString() : null);
	}

	public static String scanSessionId(Header[] cookies) {
		if (cookies == null || cookies.length == 0) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			String val = cookies[i].getValue();
			String sid = scan(val, SessionManager.SESSION_ID_KEY);
			if (sid != null) {
				return sid;
			}
		}
		return null;
	}

	private static String scan(String cookies, String key) {
		if (TextUtils.isEmpty(cookies)) {
			return null;
		}
		final String[] sa = cookies.split(";");
		final String key_ = key + "=";
		for (int i = 0; i < sa.length; i++) {
			String sai = sa[i].trim();
			if (sai.startsWith(key_)) {
				return sai.substring(key.length() + 1);
			}
		}
		return null;
	}

	/**
	 * 
	 * @param request
	 * @return true if the request is for remote host
	 */
	public static boolean isProxyRequest(HttpRequest request) {
		final String uri = request.getRequestLine().getUri();
		//quick check
		if (uri.charAt(0) == '/') {
			return false;
		}
		
		final String method = request.getRequestLine().getMethod()
		.toUpperCase(Locale.ENGLISH);

		//connect
		if (method.equals("CONNECT")) {
			//host:port
			String[] hostport = uri.split(":");
			return !isLocalHost(hostport[0]);
		}
		
		//get/post
		final Uri u = Uri.parse(uri);
		return !isLocalHost(u.getHost());
	}

	private static boolean isLocalHost(String s) {
		return (s == null || s.equalsIgnoreCase("localhost") || s.startsWith("127.0.0."));
	}

	public static boolean isProxy(HttpContext context) {
		Object h = context.getAttribute(WebConstants.BLUEWEB_PROXY_REQUEST);
		return (h != null && Boolean.valueOf(h.toString()));
	}
}
